package com.ferris.redbook.util;

import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


/**
 * 用户信息工具类，用于从请求中获取当前登录用户信息
 */
public class UserContext {

    /**
     * 获取当前请求中的用户ID
     */
    public static Long getUserId() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }
        }
        return null;
    }

    /**
     * 获取当前请求中的用户名
     */
    public static String getUsername() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            Object username = request.getAttribute("username");
            if (username != null) {
                return (String) username;
            }
        }
        return null;
    }

    /**
     * 获取当前请求中的JWT声明
     */
    public static Claims getClaims() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            Object claims = request.getAttribute("claims");
            if (claims != null) {
                return (Claims) claims;
            }
        }
        return null;
    }

    /**
     * 获取当前HTTP请求对象
     */
    private static HttpServletRequest getCurrentRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        } catch (IllegalStateException e) {
            return null;
        }
    }

    /**
     * 检查当前是否有用户登录
     */
    public static boolean isLoggedIn() {
        return getUserId() != null;
    }

    /**
     * 获取当前用户ID，如果未登录则抛出异常
     */
    public static Long requireUserId() {
        Long userId = getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        return userId;
    }

    /**
     * 获取当前用户名，如果未登录则抛出异常
     */
    public static String requireUsername() {
        String username = getUsername();
        if (username == null) {
            throw new RuntimeException("用户未登录");
        }
        return username;
    }
}